package repository

import (
	"beergo/lib/mysql"
	"beergo/lib/tool"
	"github.com/beego/beego/v2/client/orm"
	"reflect"
	"strings"
)

type BaseRepository struct {
	IsLoadRelation bool
}

func (this *BaseRepository) LoadRelation(IsLoad bool) *BaseRepository {
	if IsLoad {
		this.IsLoadRelation = true
	} else {
		this.IsLoadRelation = false
	}
	return this
}

func (this *BaseRepository) GetOrm() orm.Ormer {
	return orm.NewOrm()
}
func (this *BaseRepository) GetQuerySetter(modelOrName interface{}) orm.QuerySeter {
	o := orm.NewOrm().QueryTable(modelOrName)
	if this.IsLoadRelation {
		o = o.RelatedSel()
	}
	return o
}

type BeergoModel interface {
	GetReflect() reflect.Type
}

func (this *BaseRepository) GetRelationStringOne(qb *mysql.QueryBuilder, model BeergoModel) []interface{} {
	relations := make([]interface{}, 0)
	for _, f := range qb.Relation {
		field, ok := model.GetReflect().FieldByName(tool.Ucfirst(f))
		if ok {
			typeName := field.Type.String()
			if typeName[0:1] == "*" {
				relations = append(relations, f)
			}
		}
	}
	return relations
}

func (this *BaseRepository) GetRelationStringMany(qb *mysql.QueryBuilder, model BeergoModel) []string {
	relations := make([]string, 0)
	for _, f := range qb.Relation {
		field, ok := model.GetReflect().FieldByName(tool.Ucfirst(f))
		if ok {
			typeName := field.Type.String()
			if typeName[0:2] == "[]" {
				relations = append(relations, f)
			}
		}
	}
	return relations
}

func (this *BaseRepository) CreateSearch(qb *mysql.QueryBuilder) *orm.Condition {
	searchConf := qb.Search //格式name,tile:张三
	if searchConf != "" {
		sepFieldAndValue := strings.Split(searchConf, ":")
		if len(sepFieldAndValue) == 2 {
			searchKeysStr := sepFieldAndValue[0]
			searchKeys := strings.Split(searchKeysStr, ",")
			if len(searchKeys) > 0 {
				cond := orm.NewCondition()
				searchValue := sepFieldAndValue[1]
				for _, skey := range searchKeys {
					cond = cond.Or(skey+"__icontains", searchValue)
				}
				pCond := orm.NewCondition()
				pCond = pCond.AndCond(cond)
				return pCond
			}
		}
	}
	return nil
}
